﻿using MembersOnly.Models;
using Orchard;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Localization;
using Orchard.Security;

namespace MembersOnly.Drivers
{
    public class MembersOnlyDriver : ContentPartDriver<MembersOnlyPart>
    {
        private readonly IOrchardServices _services;

        public MembersOnlyDriver(IOrchardServices services)
        {
            _services = services;
        }

        //GET
        protected override DriverResult Editor(MembersOnlyPart part, dynamic shapeHelper)
        {
            return ContentShape("Parts_MembersOnly_Edit",
                () => shapeHelper.EditorTemplate(
                    TemplateName: "Parts/MembersOnly",
                    Model: part,
                    Prefix: Prefix));
        }

        //POST
        protected override DriverResult Editor(MembersOnlyPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part, Prefix, null, null);
            return Editor(part, shapeHelper);
        }

        protected override DriverResult Display(MembersOnlyPart part, string displayType, dynamic shapeHelper)
        {
            if (_services.WorkContext.CurrentUser == null)
                throw new OrchardSecurityException(new LocalizedString("Authenticated access only!"));

            return new DriverResult();
        }
    }
}
